package com.wxy.netty.eventLoop.io任务;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.Charset;

/**
 * @author 47868
 */
public class server {
    public static void main(String[] args) {
        //分工细化2 以防业务逻辑过于复杂 worker线程卡在一个client中 使用DefaultEventLoop处理业务逻辑较复杂的流程
        EventLoopGroup group = new DefaultEventLoop();
        new ServerBootstrap()
                //将boss与worker交给两个EventLoop
                .group(new NioEventLoopGroup(),new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {

                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) {
                        nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) {
                                ByteBuf buf = (ByteBuf) msg;
                                System.out.println(Thread.currentThread().getName()+" "+buf.toString(Charset.defaultCharset()));
                                ctx.fireChannelRead(buf);
                            }
                        }).addLast(group,new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) {
                                ByteBuf buf = (ByteBuf) msg;
                                System.out.println(Thread.currentThread().getName()+" "+buf.toString(Charset.defaultCharset()));
                            }
                        });
                    }
                })
                .bind("127.0.0.1", 8888);
    }
}
